/**
 * 人脸质量检测组件
 * 显示人脸质量检测结果和优化建议
 */

import React from 'react'
import { Toast } from 'antd-mobile'
import { CheckCircleOutline, CloseCircleOutline, ExclamationCircleOutline } from 'antd-mobile-icons'
import './FaceQualityCheck.css'

interface QualityResult {
  isValid: boolean
  message: string
  details?: {
    occlusion?: any
    blur?: number
    illumination?: number
    completeness?: number
    angle?: any
  }
}

interface FaceQualityCheckProps {
  qualityResult: QualityResult
  onRetry: () => void
  onConfirm: () => void
  isVisible: boolean
}

const FaceQualityCheck: React.FC<FaceQualityCheckProps> = ({
  qualityResult,
  onRetry,
  onConfirm,
  isVisible
}) => {
  if (!isVisible) {
    return null
  }

  const { isValid, message, details } = qualityResult

  // 获取质量检测详情
  const getQualityDetails = () => {
    if (!details) return null

    const items = []

    // 遮挡检测
    if (details.occlusion) {
      const occlusion = details.occlusion
      const occlusionItems = []
      
      if (occlusion.left_eye > 0.6) {
        occlusionItems.push('左眼被遮挡')
      }
      if (occlusion.right_eye > 0.6) {
        occlusionItems.push('右眼被遮挡')
      }
      if (occlusion.nose > 0.7) {
        occlusionItems.push('鼻子被遮挡')
      }
      if (occlusion.mouth > 0.7) {
        occlusionItems.push('嘴巴被遮挡')
      }
      if (occlusion.left_cheek > 0.8) {
        occlusionItems.push('左脸颊被遮挡')
      }
      if (occlusion.right_cheek > 0.8) {
        occlusionItems.push('右脸颊被遮挡')
      }
      if (occlusion.chin_contour > 0.6) {
        occlusionItems.push('下巴被遮挡')
      }

      if (occlusionItems.length > 0) {
        items.push({
          type: 'error',
          label: '遮挡检测',
          value: occlusionItems.join('、'),
          threshold: '建议无遮挡'
        })
      }
    }

    // 模糊度检测
    if (details.blur !== undefined) {
      items.push({
        type: details.blur >= 0.7 ? 'error' : 'success',
        label: '清晰度',
        value: `${(details.blur * 100).toFixed(1)}%`,
        threshold: '建议 < 70%'
      })
    }

    // 光照检测
    if (details.illumination !== undefined) {
      items.push({
        type: details.illumination < 40 ? 'error' : 'success',
        label: '光照强度',
        value: details.illumination.toString(),
        threshold: '建议 > 40'
      })
    }

    // 完整度检测
    if (details.completeness !== undefined) {
      items.push({
        type: details.completeness === 1 ? 'success' : 'error',
        label: '人脸完整度',
        value: details.completeness === 1 ? '完整' : '不完整',
        threshold: '建议完整'
      })
    }

    // 角度检测
    if (details.angle) {
      const { yaw, pitch, roll } = details.angle
      const angleItems = []
      
      if (Math.abs(yaw) > 20) {
        angleItems.push(`左右偏转 ${Math.abs(yaw).toFixed(1)}°`)
      }
      if (Math.abs(pitch) > 20) {
        angleItems.push(`上下偏转 ${Math.abs(pitch).toFixed(1)}°`)
      }
      if (Math.abs(roll) > 20) {
        angleItems.push(`旋转 ${Math.abs(roll).toFixed(1)}°`)
      }

      if (angleItems.length > 0) {
        items.push({
          type: 'error',
          label: '姿态角度',
          value: angleItems.join('、'),
          threshold: '建议 < 20°'
        })
      }
    }

    return items
  }

  const qualityDetails = getQualityDetails()

  return (
    <div className="face-quality-overlay">
      <div className="face-quality-container">
        {/* 头部 */}
        <div className="face-quality-header">
          <div className="face-quality-icon">
            {isValid ? (
              <CheckCircleOutline className="success-icon" />
            ) : (
              <CloseCircleOutline className="error-icon" />
            )}
          </div>
          <h3 className="face-quality-title">
            {isValid ? '质量检测通过' : '质量检测未通过'}
          </h3>
        </div>

        {/* 主要信息 */}
        <div className="face-quality-message">
          <p className="message-text">{message}</p>
        </div>

        {/* 详细检测结果 */}
        {qualityDetails && qualityDetails.length > 0 && (
          <div className="face-quality-details">
            <h4 className="details-title">检测详情</h4>
            <div className="details-list">
              {qualityDetails.map((item, index) => (
                <div key={index} className={`detail-item ${item.type}`}>
                  <div className="detail-label">
                    <span className="label-text">{item.label}</span>
                    <span className="label-threshold">({item.threshold})</span>
                  </div>
                  <div className="detail-value">
                    {item.type === 'error' ? (
                      <ExclamationCircleOutline className="error-icon" />
                    ) : (
                      <CheckCircleOutline className="success-icon" />
                    )}
                    <span className="value-text">{item.value}</span>
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* 优化建议 */}
        {!isValid && (
          <div className="face-quality-suggestions">
            <h4 className="suggestions-title">优化建议</h4>
            <ul className="suggestions-list">
              <li>确保光线充足，避免背光</li>
              <li>保持人脸正面面对摄像头</li>
              <li>避免遮挡面部特征（眼睛、鼻子、嘴巴）</li>
              <li>保持稳定，避免晃动</li>
              <li>确保人脸完全在画面内</li>
            </ul>
          </div>
        )}

        {/* 操作按钮 */}
        <div className="face-quality-actions">
          <button
            className="action-btn retry-btn"
            onClick={onRetry}
          >
            重新拍摄
          </button>
          {isValid && (
            <button
              className="action-btn confirm-btn"
              onClick={onConfirm}
            >
              确认使用
            </button>
          )}
        </div>
      </div>
    </div>
  )
}

export default FaceQualityCheck
